#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import os
import sys
import json

def get_user_info(token):
    """获取当前用户信息"""
    headers = {
        'Content-Type': 'application/json',
        'x-yunxiao-token': token
    }
    
    url = 'https://openapi-rdc.aliyuncs.com/oapi/v1/platform/user'
    resp = requests.get(url, headers=headers)
    
    if resp.status_code != 200:
        print(f"错误: 无法获取用户信息，HTTP状态码: {resp.status_code}")
        print(resp.text)
        sys.exit(1)
        
    return resp.json()

def get_aliyun_organizations(token):
    """获取阿里云云效的组织列表"""
    headers = {
        'Content-Type': 'application/json',
        'x-yunxiao-token': token
    }
    
    url = 'https://openapi-rdc.aliyuncs.com/oapi/v1/platform/organizations'
    resp = requests.get(url, headers=headers)
    
    if resp.status_code != 200:
        print(f"错误: 无法获取组织列表，HTTP状态码: {resp.status_code}")
        print(resp.text)
        sys.exit(1)
        
    return resp.json()

def get_aliyun_namespaces(token, organization_id):
    """获取阿里云云效的代码组列表"""
    headers = {
        'Content-Type': 'application/json',
        'x-yunxiao-token': token
    }
    
    url = f'https://openapi-rdc.aliyuncs.com/oapi/v1/codeup/organizations/{organization_id}/namespaces'
    params = {
        'page': 1,
        'perPage': 100,
        'orderBy': 'updated_at',
        'sort': 'desc'
    }
    
    all_namespaces = []
    page = 1
    
    while True:
        params['page'] = page
        resp = requests.get(url, headers=headers, params=params)
        
        if resp.status_code != 200:
            print(f"错误: 无法获取代码组列表，HTTP状态码: {resp.status_code}")
            print(resp.text)
            sys.exit(1)
            
        namespaces = resp.json()
        if not namespaces:
            break
            
        all_namespaces.extend(namespaces)
        
        # 如果返回的数量小于每页数量，说明没有更多数据了
        if len(namespaces) < params['perPage']:
            break
            
        page += 1
        
    return all_namespaces

def get_aliyun_repos_by_namespace(token, organization_id, namespace_id=None):
    """获取阿里云云效指定组织下的所有仓库"""
    headers = {
        'Content-Type': 'application/json',
        'x-yunxiao-token': token
    }
    
    all_repos = []
    page = 1
    per_page = 100
    
    params = {
        'page': page,
        'perPage': per_page,
        'orderBy': 'created_at',
        'sort': 'desc'
    }
    
    # 如果指定了命名空间ID，添加到查询参数中
    if namespace_id:
        params['namespaceId'] = namespace_id
    
    while True:
        # 获取组织的仓库列表
        url = f'https://openapi-rdc.aliyuncs.com/oapi/v1/codeup/organizations/{organization_id}/repositories'
        resp = requests.get(url, headers=headers, params=params)
        
        if resp.status_code != 200:
            print(f"错误: 无法获取仓库列表，HTTP状态码: {resp.status_code}")
            print(resp.text)
            sys.exit(1)
            
        repos = resp.json()
        if not repos:
            break
        
        for repo in repos:
            # 构建正确的path和SSH URL
            repo_path = repo.get('path', '')
            path_with_namespace = repo.get('pathWithNamespace', '')
            
            # 解析完整路径以获取组织名和分组名
            parts = path_with_namespace.split('/')
            if len(parts) >= 2:
                organization_name = parts[0]
                group_name = parts[1] if len(parts) > 2 else ""
                
                # 构建正确的SSH URL格式
                ssh_url = f"git@codeup.aliyun.com:{organization_name}/{group_name}/{repo_path}.git"
                
                all_repos.append({
                    'name': repo.get('name', ''),
                    'path': repo_path,
                    'path_with_namespace': path_with_namespace,
                    'organization_name': organization_name,
                    'group_name': group_name,
                    'namespace_id': repo.get('namespaceId', ''),
                    'description': repo.get('description', ''),
                    'visibility': repo.get('visibility', 'private'),
                    'ssh_url': ssh_url
                })
            
        # 检查是否还有下一页
        if len(repos) < per_page:
            break
            
        page += 1
    
    return all_repos

def sanitize_filename(name):
    """将名称转换为有效的文件名"""
    invalid_chars = '<>:"/\\|?*'
    for char in invalid_chars:
        name = name.replace(char, '_')
    return name

def main():
    # 设置认证信息
    aliyun_token = os.environ.get('ALIYUN_TOKEN')
    aliyun_org_id = os.environ.get('ALIYUN_ORG_ID')
    
    try:
        # 获取用户信息
        user_info = get_user_info(aliyun_token)
        print(f"当前用户: {user_info.get('name', '')} ({user_info.get('email', '')})")
        
        # 获取组织列表
        organizations = get_aliyun_organizations(aliyun_token)
        print(f"已找到 {len(organizations)} 个组织")
        
        # 获取当前组织信息
        org_name = ""
        for org in organizations:
            if org.get('id') == aliyun_org_id:
                org_name = org.get('name', '')
                print(f"当前组织: {org_name} (ID: {aliyun_org_id})")
                break
        
        # 获取代码组列表
        namespaces = get_aliyun_namespaces(aliyun_token, aliyun_org_id)
        print(f"已找到 {len(namespaces)} 个代码组")
        
        # 将代码组信息保存到字典中，方便后续查询
        namespace_dict = {}
        for namespace in namespaces:
            namespace_id = namespace.get('id')
            if namespace_id:
                namespace_dict[namespace_id] = namespace
        
        # 将代码组名称写入group.txt
        with open('group.txt', 'w', encoding='utf-8') as f:
            for namespace in namespaces:
                group_name = namespace.get('name', '')
                if group_name:
                    f.write(f"{group_name}\n")
        
        print(f"已将 {len(namespaces)} 个代码组名称写入 group.txt")
        
        # 获取所有仓库并按代码组分类
        repos_by_group = {}
        
        # 获取所有代码仓库
        all_repos = get_aliyun_repos_by_namespace(aliyun_token, aliyun_org_id)
        print(f"已找到 {len(all_repos)} 个代码仓库")
        
        # 按代码组分类仓库
        for repo in all_repos:
            group_name = repo.get('group_name', '')
            if group_name:
                if group_name not in repos_by_group:
                    repos_by_group[group_name] = []
                repos_by_group[group_name].append(repo)
        
        # 为每个代码组创建单独的文件
        for group_name, repos in repos_by_group.items():
            # 将代码组名称处理为有效的文件名
            filename = sanitize_filename(group_name) + '.txt'
            with open(filename, 'w', encoding='utf-8') as f:
                for repo in repos:
                    f.write(f"{repo['ssh_url']}\n")
            print(f"已将 {len(repos)} 个仓库的SSH地址写入 {filename}")
        
    except Exception as e:
        print(f"执行过程中出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main() 